//
//  SLInformationViewController.m
//  SaltLightDemo
//
//  Created by lzy on 2018/4/25.
//  Copyright © 2018年 lzy. All rights reserved.
//

#import "SLInformationViewController.h"
#import "MJRefresh.h"
#import "ProductTableViewCell.h"
#import "ProductDetailsViewController.h"
#import "QZConditionFilterView.h"
#import "UIView+Extension.h"
#import "MGRequestService+My.h"

// iPhone X 宏定义
#define  iPhoneX (SCREEN_WIDTH == 375.f && SCREEN_HEIGHT == 812.f ? YES : NO)
// 适配iPhone X 状态栏高度
#define  MC_StatusBarHeight      (iPhoneX ? 88.f : 64.f)

@interface SLInformationViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    // *存储* 网络请求url中的筛选项 数据来源：View中_dataSource1或者一开始手动的初值
    NSArray *_selectedDataSource1Ary;
    NSArray *_selectedDataSource2Ary;
    NSArray *_selectedDataSource3Ary;
    
    QZConditionFilterView *_conditionFilterView;
}
@property(nonatomic,strong)UITableView * table;
@property(nonatomic,strong)NSMutableArray * noteArray;
@property (nonatomic,assign) int time;
@property (nonatomic,assign) int i;
@property (nonatomic,strong) NSTimer *timer;//模拟数据刷新需要的时间控制器
@property (nonatomic , strong) UIButton *backBtn;

@property (nonatomic , strong) NSMutableArray *dataArray;

@property (nonatomic,assign) int pageIndex;

@property (nonatomic,assign) int ajlx;
@property (nonatomic,assign) int edpx;
@property (nonatomic,assign) int lxpx;

@end

@implementation SLInformationViewController
-(void)setType:(int)type
{
    _type = type;
//    *       0-->额度高
//    *       1-->利息低
//    *       2-->抵押贷
//    *       3-->信用贷
    if (type == 1) {
        self.edpx = 1;
    }else if (type == 2) {
        self.lxpx = 2;
    }else if (type == 3) {
        self.ajlx = 85;
    }else if (type == 4) {
        self.ajlx = 86;
    }
}
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
-(NSMutableArray *)noteArray
{
    if (!_noteArray) {
        _noteArray = [NSMutableArray array];
    }
    return _noteArray;
}
-(UITableView *)table
{
    if (!_table) {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, MC_StatusBarHeight+40, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-(self.navigationController.viewControllers.count>1?0:49)-MC_StatusBarHeight-44)];
        _table.delegate = self;
        _table.dataSource = self;
        _table.showsVerticalScrollIndicator = NO;
        _table.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [_table registerNib:[UINib nibWithNibName:@"ProductTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell4"];
        
        UIView * v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
        v.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
        
        [_table setTableFooterView:v];
        [self.view addSubview:_table];
    }
    return _table;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"贷款产品";
    self.pageIndex = 1;
    if (self.navigationController.viewControllers.count>1) {
        self.navigationItem.hidesBackButton = YES;
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        self.backBtn = button1;
        [button1 setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
        button1.frame = CGRectMake(17, 0, 50, 44);
        [button1 addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        button1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [button1 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        button1.titleLabel.font = [UIFont systemFontOfSize:16];
        [button1 setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [button1 setTitle:@"" forState:UIControlStateNormal];
        [self.navigationController.navigationBar addSubview:button1];
    }
    
    // FilterBlock 选择下拉菜单选项触发
    _conditionFilterView = [QZConditionFilterView conditionFilterViewWithFilterBlock:^(BOOL isFilter, NSArray *dataSource1Ary, NSArray *dataSource2Ary, NSArray *dataSource3Ary) {
        
        // 1.isFilter = YES 代表是用户下拉选择了某一项
        // 2.dataSource1Ary 选择后第一组选择的数据  2 3一次类推
        // 3.如果你的项目没有清空筛选条件的功能，可以无视else 我们的app有清空之前的条件，重置，所以才有else的逻辑
        
        if (isFilter) {
            //网络加载请求 存储请求参数
            _selectedDataSource1Ary = dataSource1Ary;
            _selectedDataSource2Ary = dataSource2Ary;
            _selectedDataSource3Ary = dataSource3Ary;
        }else{
            // 不是筛选，全部赋初值（在这个工程其实是没用的，因为tableView是选中后必选的，即一旦选中就没有空的情况，但是如果可以清空筛选条件的时候就有必要 *重新* reset data）
            if (self.type == 1) {
                _selectedDataSource1Ary = @[@"按揭类型"];
                _selectedDataSource2Ary = @[@"高"];
                _selectedDataSource3Ary = @[@"利息排序"];
            }else if (self.type == 2) {
                _selectedDataSource1Ary = @[@"按揭类型"];
                _selectedDataSource2Ary = @[@"额度排序"];
                _selectedDataSource3Ary = @[@"低"];
            }else if (self.type == 3) {
                _selectedDataSource1Ary = @[@"抵押贷"];
                _selectedDataSource2Ary = @[@"额度排序"];
                _selectedDataSource3Ary = @[@"利息排序"];
            }else if (self.type == 4) {
                _selectedDataSource1Ary = @[@"信用贷"];
                _selectedDataSource2Ary = @[@"额度排序"];
                _selectedDataSource3Ary = @[@"利息排序"];
            }
            
        }
        
//        // 开始网络请求
        [self startRequest];
    }];
    
    
    _conditionFilterView.y += MC_StatusBarHeight;
    NSLog(@"type==  %d",self.type);
    // 设置初次加载显示的默认数据 即初次加载还没有选择操作之前要显示的标题数据
    if (self.type == 1) {
        _selectedDataSource1Ary = @[@"按揭类型"];
        _selectedDataSource2Ary = @[@"高"];
        _selectedDataSource3Ary = @[@"利息排序"];
    }else if (self.type == 2) {
        _selectedDataSource1Ary = @[@"按揭类型"];
        _selectedDataSource2Ary = @[@"额度排序"];
        _selectedDataSource3Ary = @[@"低"];
    }else if (self.type == 3) {
        _selectedDataSource1Ary = @[@"抵押贷"];
        _selectedDataSource2Ary = @[@"额度排序"];
        _selectedDataSource3Ary = @[@"利息排序"];
    }else if (self.type == 4) {
        _selectedDataSource1Ary = @[@"信用贷"];
        _selectedDataSource2Ary = @[@"额度排序"];
        _selectedDataSource3Ary = @[@"利息排序"];
    }else
    {
        _selectedDataSource1Ary = @[@"按揭类型"];
        _selectedDataSource2Ary = @[@"额度排序"];
        _selectedDataSource3Ary = @[@"利息排序"];
    }
    
    
    // 传入数据源，对应三个tableView顺序
    _conditionFilterView.dataAry1 = @[@"按揭类型",@"抵押贷",@"信用贷"];
    _conditionFilterView.dataAry2 = @[@"额度排序",@"高",@"低"];
    _conditionFilterView.dataAry3 = @[@"利息排序",@"高",@"低"];
    
    // 初次设置默认显示数据(标题)，内部会调用block 进行第一次数据加载
    [_conditionFilterView bindChoseArrayDataSource1:_selectedDataSource1Ary DataSource2:_selectedDataSource2Ary DataSource3:_selectedDataSource3Ary];
    
    [self.view addSubview:_conditionFilterView];
    
    
    
    // Do any additional setup after loading the view.
}
-(void)goBack
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    self.backBtn.hidden = YES;
}
-(void)dealloc
{
    self.backBtn.hidden = YES;
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.backBtn.hidden = NO;
    self.i += 1;
}
- (void)startRequest
{
    
    
    NSString *source1 = [NSString stringWithFormat:@"%@",_selectedDataSource1Ary.firstObject];
    NSString *source2 = [NSString stringWithFormat:@"%@",_selectedDataSource2Ary.firstObject];
    NSString *source3 = [NSString stringWithFormat:@"%@",_selectedDataSource3Ary.firstObject];
    
    [self.dataArray removeAllObjects];
//    if (self.type && self.type>0) {
        if ([source1 isEqualToString:@"按揭类型"]) {
            self.ajlx = 0;
        }else if ([source1 isEqualToString:@"抵押贷"]) {
            self.ajlx = 85;
        }else if ([source1 isEqualToString:@"信用贷"]) {
            self.ajlx = 86;
        }
    
        if ([source2 isEqualToString:@"额度排序"]) {
            self.edpx = 0;
        }else if ([source2 isEqualToString:@"高"]) {
            self.edpx = 1;
        }else if ([source2 isEqualToString:@"低"]) {
            self.edpx = 2;
        }
    
    
    
        if ([source3 isEqualToString:@"利息排序"]) {
            self.lxpx = 0;
        }else if ([source3 isEqualToString:@"高"]) {
            self.lxpx = 1;
        }else if ([source3 isEqualToString:@"低"]) {
            self.lxpx = 2;
        }
//    }
    
    // 可以用字符串在dic换成对应英文key
    [self loadMutableRequest];
    [self initRefresh];
    NSLog(@"\n第一个条件:%@\n  第二个条件:%@\n  第三个条件:%@\n",source1,source2,source3);
    
}
- (void)loadMutableRequest
{
    
    [MGRequestService requestgetProductListWithtype:self.ajlx andorderAmount:self.edpx andorderTerm:self.lxpx andpageIndex:self.pageIndex andpageSize:10 success:^(MGBaseRspModel *model) {
        
        if (model.resultCode == 0) {
            if ([self.table.mj_header isRefreshing]) {
                [self.dataArray removeAllObjects];
            }
            [self.dataArray addObjectsFromArray:(NSArray *)model.respData];
            self.table.backgroundColor = [UIColor whiteColor];
            [self.table reloadData];
            
            NSLog(@"一共 %lu",(unsigned long)self.dataArray.count);
            
            if ([self.table.mj_header isRefreshing])
            {
                [self.table.mj_header endRefreshing];
            }
            
            if ([self.table.mj_footer isRefreshing])
            {
                [self.table.mj_footer endRefreshing];
            }
        }else
        {
            [self showToastInViewController:model.errorMessage];
        }
    } failure:^(NSError *error) {
        [self showToastInViewController:@"网络出错"];
    }];
    
    
}
/**
 *  刷新数据
 */
-(void)initRefresh
{
    __weak __typeof(self) weakSelf = self;
    MJRefreshNormalHeader *header =[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    self.table.mj_header = header;
    self.table.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMoreData];
    }];
}
-(void)loadMoreData{
    self.timer  =[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timeAction1) userInfo:nil repeats:YES];
    self.time = 1;
}
-(void)timeAction1 {
    self.time --;
    
    if (self.time == 0) {
        
        self.pageIndex ++;
        [self loadMutableRequest];
        //        //        停止刷新
       
        [self.timer invalidate];
    }
}
-(void)loadNewData {
    //模拟刷新的时间
    
    self.timer  =[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    self.time = 1;
}
-(void)timeAction {
    self.time --;
    
    if (self.time == 0) {
        self.pageIndex = 1;
        
        [self loadMutableRequest];
        //        //        停止刷新
//        [self.table.mj_header endRefreshing];
        [self.timer invalidate];
    }
}

//table代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProductTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell4" forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary * dic = self.dataArray[indexPath.section];
    if([dic[@"type"] intValue] == 85)
    {
        cell.label1.text = @"抵押贷";
    }else{
        cell.label1.text = @"信用贷";
    }
    cell.name.text =dic[@"name"];
    
    cell.edlabel.text =[NSString stringWithFormat:@"%d-%d万",dic[@"amountMin"]?[dic[@"amountMin"] intValue]/10000:0,dic[@"amountMax"]?[dic[@"amountMax"] intValue]/10000:0];
    cell.nianxian.text =[dic[@"termType"] intValue] == 1?[NSString stringWithFormat:@"%@-%@月",([NSString stringWithFormat:@"%@",dic[@"termMin"]].length<=0?@"0":dic[@"termMin"]),dic[@"termMax"]]:[NSString stringWithFormat:@"%@-%@年",([NSString stringWithFormat:@"%@",dic[@"termMin"]].length<=0?@"0":dic[@"termMin"]),dic[@"termMax"]];
    cell.yuell.text =([dic[@"monthRateMin"] floatValue]<=0 ||[dic[@"monthRateMax"] floatValue]<=0)?@"面议":[NSString stringWithFormat:@"%@-%@%@",dic[@"monthRateMin"],dic[@"monthRateMax"],@"%"];
    [cell setSeeBlock:^{
        ProductDetailsViewController * ctr = [[ProductDetailsViewController alloc]init];
        ctr.type = [dic[@"id"] intValue];
        [self.navigationController pushViewController:ctr animated:YES];
    }];
    return cell;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 10;
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    view.backgroundColor = [UIColor add_colorWithRGBHexString:@"EFEFF4"];
    return view;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
